package com.innovation.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import org.apache.log4j.Logger;

import com.innovation.cmd.Command;
import com.innovation.cmd.CommandSet;
import com.innovation.message.ServerMessageProto.ServerMessage;

public class SocketServerHandler extends SimpleChannelInboundHandler<ServerMessage> {
	
	private static Logger logger = Logger.getLogger(SocketServerHandler.class);
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ServerMessage msg) throws Exception {
		ServerMessage request = msg;
		int code = request.getCmdCode();
		try{
			logger.info("recv message:"+ctx.channel());
			Command cmd = CommandSet.INSTANCE.getCommand(code);
			ServerMessage.Builder response = cmd.execute(request);
			response.setCmdCode(code);
			ctx.channel().writeAndFlush(response.build());
		}catch (Exception e) {
			logger.error("execute command code="+code+" error.", e);
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
		cause.fillInStackTrace();
		ctx.channel().close();
	}
}
